package com.fxkj.cloud.drms.infra.ws;

import com.fxkj.common.constants.OrgArtConstants;
import com.fxkj.common.constants.ServiceConstants;
import com.fxkj.common.constants.UserInfoConstants;
import com.fxkj.common.model.UserInfo;
import com.fxkj.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.*;
import java.util.stream.Stream;

/**
 * <p>description: </p>
 * @author ww
 * @date 2025/3/17 18:49
 */
@Slf4j
public class UserInfoHandshakeInterceptor implements HandshakeInterceptor {
    public static final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol";
    /**
     * 构造函数
     * @param subProtocols 支持的子协议集合
     */

    /**
     * 在握手之前执行, 这里不做任何处理, 主要逻辑在 `afterHandshake` 中实现
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        List<String> protocols = request.getHeaders().get(SEC_WEBSOCKET_PROTOCOL);
        if (null == protocols || protocols.size() == 0) {
            return false;
        }
        response.getHeaders().add(SEC_WEBSOCKET_PROTOCOL, protocols.getFirst());
        return true;
    }

    /**
     * 在握手之后执行，用于处理子协议
     *  @param request  请求信息
     * @param response  响应信息
     * @param wsHandler websocket处理器
     * @param exception 异常信息
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        try {
            List<String> skipStrs = request.getHeaders().getOrEmpty(ServiceConstants.SKIP_HEADER);
            if (null != skipStrs && skipStrs.size() > 0) {
                String skip = skipStrs.getFirst();
                if (!StringUtils.isEmpty(skip)) {
                    return;
                }
            }
            String userIdHeader = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.USER_ID)).getFirst();
            if (StringUtils.isEmpty(userIdHeader)) {
                return;
            }
            UUID userId = UUID.fromString(userIdHeader);
            String username = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.USERNAME)).getFirst();
            String avatar = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.AVATAR)).getFirst();
            String firstname = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.FIRSTNAME)).getFirst();
            String lastname = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.LASTNAME)).getFirst();
            String phone = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.PHONE)).getFirst();
            String email = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.EMAIL)).getFirst();

            String roleHeader = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.ROLES)).getFirst();
            List<String> roles = new ArrayList<>();
            if (!StringUtils.isEmpty(roleHeader) && roleHeader.contains(",")) {
                roles = List.of(roleHeader.split(","));
            }

            List<String> permissionStrings = request.getHeaders().get(UserInfoConstants.PERMISSIONS);
            List<String> permissions = new ArrayList<>();
            if (null!=permissionStrings){
                String permissionHeader = permissionStrings.getFirst();
                if (!StringUtils.isEmpty(permissionHeader) && permissionHeader.contains(",")) {
                    permissions = List.of(permissionHeader.split(","));
                }
            }

            String orgHeader = Objects.requireNonNull(request.getHeaders().get(UserInfoConstants.ORGANIZATIONS)).getFirst();
            List<UUID> organizations = new ArrayList<>();
            if (!StringUtils.isEmpty(orgHeader) && orgHeader.contains(",")) {
                organizations = Stream.of(orgHeader.split(",")).map(UUID::fromString).toList();
            }

            UUID orgId = UUID.fromString(Objects.requireNonNull(request.getHeaders().get(OrgArtConstants.ORG_ID)).getFirst());
            UUID rootOrgId = UUID.fromString(Objects.requireNonNull(request.getHeaders().get(OrgArtConstants.ROOT_ORG_ID)).getFirst());

            List<String> remarkStrings = request.getHeaders().get(UserInfoConstants.REMARK);
            String remark = null;
            if (null!=remarkStrings){
                remark = remarkStrings.getFirst();
            }

            UserContext.setUserInfo(new UserInfo(userId, username, avatar, firstname, lastname, phone, email, roles, permissions, organizations, remark, orgId, rootOrgId));
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("用户信息解析失败");
        }
    }
}